import { reactive, ref } from 'vue'
import { useUserStore } from '@/stores/user'

export function useLogin() {
  const userStore = useUserStore()

  // 表单数据
  const form = reactive({
    username: '',
    password: '',
  })

  // 状态管理
  const loading = ref(false)
  const showPassword = ref(false)
  const privacyAccepted = ref(true) // 默认为true，因为当前UI没有隐私政策选择框

  // Logo图片
  const logoImage = ref('/static/logo.png')

  async function beforeLogin() {
    // #ifdef MP-WEIXIN
    uni.login({
      provider: 'weixin', // 使用微信登录
      success(loginRes) {
        console.log(loginRes.errMsg, loginRes.code)
        if (loginRes.errMsg === 'login:ok') {
          handleLogin(loginRes.code)
        }
      },
    })
    // #endif
    // #ifdef H5
    handleLogin('ECHO-REMINIS-H5')
    // #endif
  }

  // 处理登录
  async function handleLogin(code: string) {
    if (!form.username.trim()) {
      uni.showToast({
        title: '用户名不能为空',
        icon: 'none',
      })
      return
    }

    if (form.password.length < 6) {
      uni.showToast({
        title: '请输入正确密码，密码至少6位',
        icon: 'none',
      })
      return
    }

    loading.value = true

    try {
      const success = await userStore.login(form.username, form.password, code)

      if (success) {
        uni.showToast({
          title: '登录成功',
          icon: 'success',
        })

        setTimeout(() => {
          const pages = getCurrentPages()
          const currentPage = pages[pages.length - 1] as any
          const redirect = currentPage?.options?.redirect || currentPage?.$page?.options?.redirect

          if (redirect) {
            const decodedUrl = decodeURIComponent(redirect)
            if (decodedUrl.startsWith('/pages/home/') || decodedUrl.startsWith('/pages/message/') || decodedUrl.startsWith('/pages/setting/')) {
              uni.switchTab({ url: decodedUrl })
            }
            else {
              uni.redirectTo({
                url: decodedUrl,
                fail: () => {
                  uni.switchTab({ url: '/pages/home/index' })
                },
              })
            }
          }
          else {
            uni.switchTab({ url: '/pages/home/index' })
          }
        }, 1500)
      }
    }
    catch (error: any) {
      uni.showToast({
        title: error?.message || '登录失败',
        icon: 'none',
      })
      form.password = ''
      loading.value = false
    }
    finally {
      loading.value = false
    }
  }

  // 切换密码显示状态
  function togglePassword() {
    showPassword.value = !showPassword.value
  }

  // 微信登录
  function handleWechatLogin() {
    uni.showToast({
      title: '微信登录功能开发中...',
      icon: 'none',
    })
  }

  // 手机号登录
  function handlePhoneLogin() {
    uni.navigateTo({ url: '/pages/login/phone/index' })
  }

  // 忘记密码
  function handleForgotPassword() {
    uni.navigateTo({ url: '/pages/login/forgot/index' })
  }

  // 隐私政策
  function handlePrivacyPolicy() {
    uni.navigateTo({ url: '/pages/agreement/privacy' })
  }

  // 切换隐私政策同意状态
  function togglePrivacyAccepted() {
    privacyAccepted.value = !privacyAccepted.value
  }

  return {
    form,
    loading,
    showPassword,
    privacyAccepted,
    logoImage,
    beforeLogin,
    togglePassword,
    handleWechatLogin,
    handlePhoneLogin,
    handleForgotPassword,
    handlePrivacyPolicy,
    togglePrivacyAccepted,
  }
}
